package org.budo.mybatis.criteria.query.parser.impl;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Id;

import org.budo.support.lang.util.ReflectUtil;
import org.budo.support.lang.util.StringUtil;

/**
 * @author lmw
 */
public class SelectItem implements Serializable {
    private static final long serialVersionUID = 3521840886848702207L;

    private String fieldName;

    private Class<?> entityType;

    public SelectItem() {}

    public SelectItem(Class<?> entityType, String fieldName) {
        this.entityType = entityType;
        this.fieldName = fieldName;
    }

    public Class<?> getEntityType() {
        return entityType;
    }

    public void setEntityType(Class<?> entityType) {
        this.entityType = entityType;
    }

    public String getFieldName() {
        return fieldName;
    }

    public void setFieldName(String fieldName) {
        this.fieldName = fieldName;
    }

    public String toSql() {

        String columnPrefix = "";
        if (fieldName.contains(".")) {
            String[] fields = fieldName.split("\\.");
            for (int i = 0; i < fields.length - 1; i++) {
                entityType = ReflectUtil.getField(entityType, fields[i]).getType();
                columnPrefix += fields[i] + "_";
            }

            fieldName = fields[fields.length - 1];
        }

        List<Field> fields = ReflectUtil.getAllFields(entityType);
        for (Field field : fields) {
            if (field.getName().equals(fieldName)) {
                Id id = field.getAnnotation(Id.class);
                if (null != id) {
                    if (StringUtil.isEmpty(columnPrefix)) {
                        return "t." + field.getName();
                    } else {
                        return columnPrefix + "." + field.getName();
                    }
                }

                Column column = field.getAnnotation(Column.class);
                if (null == column) {
                    throw new RuntimeException("@Id or @Column not found, entityType=" + entityType + ", fieldName=" + fieldName);
                }

                String columnName = StringUtil.isEmpty(column.name()) ? field.getName() : column.name();
                if (StringUtil.isEmpty(columnPrefix)) {
                    return "t." + columnName;
                } else {
                    return columnPrefix + "." + columnName + " " + columnPrefix + columnName;
                }
            }
        }

        throw new RuntimeException("field not found, entityType=" + entityType + ", fieldName=" + fieldName);
    }
}